import styles from './index.less';
import { Link, useLocation, history, useHistory, useRouteMatch } from 'umi';
import ReactWeui from 'react-weui';
const {
  Footer,
  FooterText,
  Cells,
  CellsTitle,
  TextArea,
  Cell,
  CellBody,
  CellFooter,
} = ReactWeui;
import request from '@/utils/request';
import { useEffect, useState } from 'react';
import { setUserInfo } from '@/utils/auth';
import weui from 'weui.js';
import { Icon, NavBar } from 'antd-mobile';

const appid = 'wx17a43da7ecd43e0b';
const redirectUrl = 'https://h5.sssplus.cn/mp/login';

function build_authorize_url(
  appid: string,
  redirect_uri: string,
  scope: string,
  state: string,
) {
  if (!appid) {
    throw Error('appid 不能为空');
  }
  if (!redirect_uri) {
    throw Error('redirect_uri 不能为空');
  }
  let encodedRedirectUrl = encodeURI(redirect_uri);
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodedRedirectUrl}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
}

function get_snsapi_base_authorize_url(
  appid: string,
  redirect_uri: string,
  state: string,
) {
  return build_authorize_url(appid, redirect_uri, 'snsapi_base', state);
}

function get_snsapi_userinfo_authorize_url(
  appid: string,
  redirect_uri: string,
  state: string,
) {
  return build_authorize_url(appid, redirect_uri, 'snsapi_userinfo', state);
}

var historyState = {
  title: 'title',
  url: '#back',
};

export default function MpLoginPage() {
  // 公众号授权code
  const [code, setCode] = useState('');
  const [goNumber, setGoNumber] = useState(-1);

  const history = useHistory();
  console.log(history);
  const location = useLocation();
  console.log(location);
  const match = useRouteMatch();
  console.log(match);

  useEffect(() => {
    let code = location.query.code;
    setCode(code);

    // 授权跳转后返回循环问题，不过微信好像已经解决了   ==============
    // window.addEventListener("popstate", function(e) {
    //   console.log(e);
    //   alert("监听到返回按钮事件啦");
    //   //根据自己的需求实现自己的功能
    //   //window.location.href = 'https://www.baidu.com'
    // }, false);
    // window.history.pushState(historyState, historyState.title, historyState.url)
    // ================================================================================================

    // let state = location.query.state;
    // if(state){
    //   let goNumber = state.split("=")[1]
    //   setGoNumber(goNumber)
    // }
    // if (code) {
    //   handleSubmit(code);
    // }
  }, []);

  function navBarGoBack() {
    history.go(goNumber);
  }

  function handleAuthorize() {
    var loading = weui.loading('获取授权...');
    const url = get_snsapi_base_authorize_url(appid, redirectUrl, '');
    window.location.replace(url);
  }

  function handleSubmit(code: string) {
    var loading = weui.loading('登录中...');
    request('/api/jsapi/sns/oauth2/access_token', {
      method: 'POST',
      data: {
        code: code,
      },
      requestType: 'form',
    })
      .then((res) => {
        console.log(res);
        const { data } = res;
        setUserInfo(data);
        weui.toast('登录成功');
        history.goBack();
      })
      .finally(() => {
        loading.hide();
      });
  }

  return (
    <div className="page">
      {/* <div className="page__navbar">
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          leftContent="返回"
          onLeftClick={() => navBarGoBack()}
        >
        </NavBar>
      </div> */}
      <CellsTitle>Code</CellsTitle>
      <Cells>
        <Cell>
          <CellBody>
            <TextArea
              placeholder="Enter your comments"
              rows="3"
              maxLength={200}
              value={code}
            ></TextArea>
          </CellBody>
        </Cell>
      </Cells>
      <div className="weui-form">
        {/* <button
          className="weui-btn weui-btn_primary"
          onClick={() => handleAuthorize()}
        >
          snsapi_base授权
        </button> */}
        <button
          className="weui-btn weui-btn_primary"
          onClick={() => handleSubmit(code)}
        >
          登录
        </button>
        <button
          className="weui-btn weui-btn_default"
          onClick={() => history.go(goNumber)}
        >
          取消
        </button>
        <div className="weui-form__opr-area">
          {/* <button type="button" role="button" disabled={amount ? false : true} aria-disabled="true" className={`weui-btn weui-btn_primary ${amount ? '' : 'weui-btn_disabled'}`}
                        id="showTooltips" onClick={() => handleSubmit()}>下单</button> */}
        </div>
      </div>
    </div>
  );
}
